﻿/*
 * TcpServer.h
 *
 */
#ifndef __GDK_TCPSERVER_H__
#define __GDK_TCPSERVER_H__

#include <gdk/core/Types.h>
#include <gdk/core/Task.h>
#include <gdk/core/IO.h>
#include <gdk/net/Socket.h>
#include <gdk/net/TcpConnection.h>
#include <vector>
#include <algorithm>


namespace gdk
{



class GDK_NET_EXPORT TcpServer : public Socket
{
	DECLARE_CLASS_HANDLE(TcpServer)

private:
	SOCKET				_acceptSocket;

private:
	typedef std::vector<__in_addr>  NetAddressArray;
	NetAddressArray		_rejectAddress;
	NetAddressArray		_permissionAddress;


protected:
	TcpServer(void);
	~TcpServer(void);


public:
	void  addRejectAddress(struct __in_addr &addr);
	void  addPermissionAddress(struct __in_addr &addr);
	void  clearRejectAddress(void);
	void  clearpermissionAddress(void);


public:
	virtual bool listen(unsigned short port, int nConnectionBacklog = 50);
	virtual void close(void);
	virtual bool accept(TcpConnection *pConnection);
	virtual bool permission(const struct __sockaddr_in &addr);
	virtual void onTick(uint32_t timeSinceLastTick);

protected:
	virtual void onAccept(void) {}
};


__INLINE__
TcpServer::TcpServer(void)
	: _acceptSocket(INVALID_SOCKET)
{
}

__INLINE__
TcpServer::~TcpServer(void)
{
	if (!isInvalid())
	{
		TcpServer::close();
	}
}

__INLINE__
void TcpServer::addRejectAddress(struct __in_addr &addr)
{
	NetAddressArray::const_iterator it = std::find(_rejectAddress.begin(), _rejectAddress.end(), addr);
	if (it == _rejectAddress.end())
	{
		_rejectAddress.push_back(addr);
	}
}
__INLINE__
void TcpServer::addPermissionAddress(struct __in_addr &addr)
{
	NetAddressArray::const_iterator it = std::find(_permissionAddress.begin(), _permissionAddress.end(), addr);
	if (it == _permissionAddress.end())
	{
		_permissionAddress.push_back(addr);
	}
}
__INLINE__
void TcpServer::clearRejectAddress(void)
{
	_rejectAddress.clear();
}
__INLINE__
void TcpServer::clearpermissionAddress(void)
{
	_permissionAddress.clear();
}



}//namespace gdk



#endif /*__GDK_TCPSERVER_H__*/
